package com.example.service.impl;

import com.example.entity.Staff;
import com.example.mapper.StaffMapper;
import com.example.service.IStaffService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nanhang.common.util.PageResult;
import com.example.entity.Department;
import com.example.service.IDepartmentService;
import com.example.vo.StaffVO;
import org.springframework.beans.factory.annotation.Autowired;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wmj
 * @since 2025-01-12
 */
@Service
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff> implements IStaffService {
    @Autowired
    private IDepartmentService departmentService;
    // 1. 分页查询
    @Override
    public PageResult<Staff> findByPage(Integer page, Integer pageSize) {
        // 1. 开始分页
        Page<Staff> page1 = this.page(new Page<>(page, pageSize));

        // 2. 封装分页结果
        return new PageResult<>(page1.getRecords(),page1.getTotal());
    }

    // 3. 条件带分页查询
    @Override
    public PageResult<Staff> search(Integer page, Integer pageSize, StaffVO vo) {
        // 1. 进行分页带条件查询
        // 1.1 封装查询条件
        QueryWrapper<Staff> wrapper = new QueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(vo.getSname()), "sname",  vo.getSname() )
                .like(StrUtil.isNotBlank(vo.getAddr()), "addr", vo.getAddr())
                .eq(vo.getDid() != null && vo.getDid() != 0, "did", vo.getDid());
        // 1.2 开始分页查询
        Page<Staff> page1 = this.page(new Page<>(page, pageSize), wrapper);
        // 1.3 处理学生所在班级名称
        page1.getRecords().forEach(st -> {
            Department department = departmentService.getById(st.getDid());
            st.setDname(department.getDname());
        });
        // 2. 封装分页结果
        return new PageResult<>(page1.getRecords(),page1.getTotal());
    }

    // 添加学生
    @Override
    public boolean add(Staff staff) {
        return this.save(staff);
    }
}
